<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\BaseConfig;
use app\airobot\model\OriginForge;
use app\airobot\model\Product;
use think\admin\Controller;
use think\facade\Db;

/**
 * 超管系统-Forge管理
 * Class Forge
 * @package app\airobot\controller
 */
class Forge extends Controller
{
    private $table = 'forge';
    public $commonLogic;

    /**
     * 盒子列表
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = 'Forge列表';
        $query = $this->_query($this->table);
        $where = [];
        if (!empty($_GET['product_id'])) {
            $where['product_id'] = $_GET['product_id'];
        }
        $query->where($where);
        $query->order('id asc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        $this->commonLogic = new CommonLogic();
        $ImageUrl = CommonLogic::GetImageUrl();

        // 商品
        $productIds = [];
        foreach ($data as $vo) {
            $productIds[] = $vo["product_id"];
        }
        $productIds = array_unique($productIds);
        $productModel = new Product();
        $productList = $productModel->queryList([], ['field' => 'id', 'data' => $productIds], [], [], [], "", $field = "*", $order = "");
        $productMap = array_column($productList, null, 'id');
        foreach ($data as &$vo) {
            $vo = $this->dealDecimal($vo);
            $vo['default_spin_amount'] = $this->commonLogic->DealAmount($vo['default_spin_amount']);
            $vo['product_amount'] = isset($productMap[$vo['product_id']]) ? $this->commonLogic->DealAmount($productMap[$vo['product_id']]['amount']) : 0;
            $vo['product_image'] = isset($productMap[$vo['product_id']]) ? $ImageUrl['product'] . $productMap[$vo['product_id']]['image'] : "";
            $vo['head_image'] = $ImageUrl['forge_head'] . $vo['head_image'];
        }
    }

    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $this->commonLogic = new CommonLogic();
        $list = Db::table('forge')->select()->toArray();
        foreach ($list as &$vo) {
            // spin金额
            $vo = $this->dealDecimal($vo);
            // rtp
            $rtpArr = json_decode($vo["rtp"], true);
            $index = 0;
            foreach ($rtpArr as $k => $rtpItem) {
                $vo["RTP" . (++$index)] = $k . "==" . $rtpItem;
            }
        }

        // 设置 CSV 文件的名字
        $filename = "forge.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['id', '商品ID', '是否热门(0否,1是)', '头像', '默认spin金额', '默认中奖概率', '最低概率', '最高概率', 'rtp_base', 'rtp_corr', 'corr_value', 'k_ban']);

        // 写入数据行
        foreach ($list as $k => $v) {
            fputcsv($output, [$v['id'], $v['product_id'], $v['is_hot'], $v['head_image'], $v['default_spin_amount'], $v['forge_probability'], $v['min_probability'], $v['max_probability'], $v['rtp_base'], $v['rtp_corr'], $v['corr_value'], $v['k_ban']]);
        }

        // 关闭输出流
        fclose($output);
    }

    public function dealDecimal($data)
    {
        foreach ($data as $key => $value) {
            if ($key == "forge_probability" ||
                $key == "min_probability" ||
                $key == "max_probability" ||
                $key == "rtp_base" ||
                $key == "rtp_corr" ||
                $key == "corr_value" ||
                $key == "k_ban" ||
                $key == "default_spin_amount") {
                $data[$key] = floatval($value);
            }
        }
        return $data;
    }

    /**
     * 添加数据字典
     * @auth true
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->checkCreateAndEdit(false);
            $createData = [];
            $createData["is_hot"] = $data["is_hot"];
            $createData["default_spin_amount"] = $data["default_spin_amount"];
            $createData["forge_probability"] = $data["forge_probability"];
            $createData["product_id"] = $data["product_id"];
            $createData["min_probability"] = $data["min_probability"];
            $createData["max_probability"] = $data["max_probability"];
            $createData["rtp_base"] = $data["rtp_base"];
            $createData["rtp_corr"] = $data["rtp_corr"];
            $createData["corr_value"] = $data["corr_value"];
            $createData["k_ban"] = $data["k_ban"];
            $createData["status"] = 1;
            $forgeModel = new \app\airobot\model\Forge();
            $forgeModel->createInfo($createData);
            $this->success("保存成功！");
        } else {
            OriginForge::mForm('form');
        }
    }

    /**
     * 编辑数据字典
     * @auth true
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $this->checkCreateAndEdit(true);
            $this->success("保存成功！");
        }

        $forgeModel = new \app\airobot\model\Forge();
        $vo = $forgeModel->queryInfo(["id" => $_GET["id"]]);
        $this->vo = $this->dealDecimal($vo);
        OriginForge::mForm('form');
    }

    public function checkCreateAndEdit($isUpdate = true)
    {
        $returnData = [];
        if ($this->request->isPost()) {
            if ($_POST["product_id"] == "") {
                $this->error("商品ID错误！");
            }
            if ($_POST["forge_probability"] == "" || $_POST['forge_probability'] <= 0 || $_POST['forge_probability'] >= 1) {
                $this->error("默认中奖概率错误！");
            }
            if ($_POST["min_probability"] == "" || $_POST['min_probability'] <= 0 || $_POST['min_probability'] >= 1) {
                $this->error("最小概率错误！");
            }
            if ($_POST["max_probability"] == "" || $_POST['max_probability'] <= 0 || $_POST['max_probability'] >= 1) {
                $this->error("最大概率错误！");
            }
            if ($_POST["default_spin_amount"] == "") {
                $this->error("默认Spin金额错误！");
            }
            if ($_POST["rtp_base"] == "" || $_POST['rtp_base'] <= 0 || $_POST['rtp_base'] >= 100) {
                $this->error("rtp_base错误！");
            }
            if ($_POST["rtp_corr"] == "" || $_POST['rtp_corr'] <= 0 || $_POST['rtp_corr'] >= 100) {
                $this->error("rtp_corr错误！");
            }
            if ($_POST["corr_value"] == "" || $_POST['corr_value'] <= 0) {
                $this->error("corr_value错误！");
            }
            if ($_POST["k_ban"] == "" || $_POST['k_ban'] <= 0 || $_POST['k_ban'] >= 1) {
                $this->error("k_ban错误！");
            }
            $productModel = new Product();

            // 展示商品校验
            $productInfo = $productModel->queryInfo(["id" => $_POST["product_id"]]);
            if (is_null($productInfo) || $productInfo['id'] != $_POST["product_id"]) {
                $this->error("未查到商品信息！");
            }
            if ($_POST['default_spin_amount'] <= 0 || $_POST['default_spin_amount'] >= $productInfo["amount"]) {
                $this->error("默认Spin金额错误！");
            }

            // RTP格式校验
            if ($isUpdate) {
                $forgeModel = new \app\airobot\model\Forge();
                $forgeModel->updateInfo(["id" => $_POST["id"]], $_POST);
            }
            $returnData = $_POST;
        }

        return $returnData;
    }

    /**
     * 状态
     * @auth true
     */
    public function status()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:1,2,3,4,5' => '状态值范围异常！',
            'status.require' => '状态值错误！',
        ]), 'id');
    }

    /**
     * 删除
     * @auth true
     */
    public function remove()
    {
        $this->_delete($this->table, 'id');
    }
}